import React, { useEffect, useState } from 'react';
import { View, Text, SafeAreaView, Image, TouchableOpacity, TextInput, ScrollView, Modal, Alert } from 'react-native';
import { Toast } from '@ant-design/react-native';
import { launchCamera, launchImageLibrary, ImagePickerResponse } from 'react-native-image-picker';
import { styles } from './styles';
import { getTaskDetailApi, getProcessTaskDetailApi, pushWorkApi, inStationApi, outStationApi, getWorkListApi, pushIPQCApi, callDeviceApi, callLogisticsApi, bindMesTrayApi, callAccidentApi, callMaterialClaimApi, callToolsClaimApi, callKnifeClaimApi, callMaterialRefundApi, callToolsRefundApi, callKnifeRefundApi, pushFAIApi, getMesTaskHandoverListApi, saveOrUpdateMesTaskHandoverApi } from './api';

interface ProductionReportProps {
    onBackPress?: () => void;
    apiData?: any;
}

const ProductionReport: React.FC<ProductionReportProps> = ({ onBackPress, apiData }) => {
    const [taskDetailData, setTaskDetailData] = useState<any>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [workQuantity, setWorkQuantity] = useState('0');
    const [fatalQuantity, setFatalQuantity] = useState('0');
    const [currentProcessIndex, setCurrentProcessIndex] = useState(0);
    const [workListData, setWorkListData] = useState<any[]>([]);
    const [showWorkList, setShowWorkList] = useState(false);
    const [isLoadingWorkList, setIsLoadingWorkList] = useState(false);
    const [showTrayModal, setShowTrayModal] = useState(false);
    const [trayNum, setTrayNum] = useState('');
    const [workListType, setWorkListType] = useState<'inspection' | 'records' | null>(null);
    const [handoverListData, setHandoverListData] = useState<any[]>([]);
    const [showHandoverList, setShowHandoverList] = useState(false);
    const [isLoadingHandoverList, setIsLoadingHandoverList] = useState(false);
    const [showImageModal, setShowImageModal] = useState(false);
    const [previewImageUrl, setPreviewImageUrl] = useState('');
    const [showHandoverModal, setShowHandoverModal] = useState(false);
    const [handoverRemark, setHandoverRemark] = useState('');
    const [handoverImages, setHandoverImages] = useState<string[]>([]);

    useEffect(() => {
        // 记录API返回的数据
        console.log('=== ProductionReport页面接收到的API数据 ===');
        console.log('完整数据:', apiData);
        console.log('数据类型:', typeof apiData);
        if (apiData) {
            console.log('数据键值:', Object.keys(apiData));
            console.log('数据值:', Object.values(apiData));
        }
        console.log('========================================');

        // 如果API数据存在且包含data字段，则调用获取任务详情接口
        if (apiData && apiData.data && apiData.data.batch_order_num) {
            fetchTaskDetail(apiData.data.batch_order_num);
        }
    }, [apiData]);

    const fetchTaskDetail = async (batchOrderNum: string) => {
        setIsLoading(true);
        try {
            console.log('开始获取任务详情，批次订单号:', batchOrderNum);
            const response = await getTaskDetailApi(batchOrderNum);

            if (response.code === 200) {
                console.log('获取任务详情成功');
                setTaskDetailData(response.data);
                // 设置当前工序索引（根据当前任务的mbom_id找到对应的索引）
                if (response.data.task && response.data.bom_list) {
                    const currentMbomId = response.data.task.mbom_id;
                    const currentIndex = response.data.bom_list.findIndex((bom: any) => bom.id === currentMbomId);
                    setCurrentProcessIndex(currentIndex >= 0 ? currentIndex : 0);
                }
            } else {
                console.error('获取任务详情失败:', response.msg);
                Toast.fail(response.msg || '获取任务详情失败');
            }
        } catch (error) {
            console.error('获取任务详情接口调用失败:', error);
            Toast.fail('网络请求失败，请重试');
        } finally {
            setIsLoading(false);
        }
    };

    const handleProcessPress = async (index: number, bom: any) => {
        if (!taskDetailData) return;

        try {
            console.log('切换工序:', bom.process_name);
            const response = await getProcessTaskDetailApi(
                taskDetailData.task.batch_order_id,
                bom.id
            );

            if (response.code === 200) {
                console.log('切换工序成功');
                setTaskDetailData(response.data);
                setCurrentProcessIndex(index);
                // 清空输入框
                setWorkQuantity('0');
                setFatalQuantity('0');

                // 如果当前显示的是报工列表，则重新获取列表数据
                if (showWorkList) {
                    await handleGetWorkList(workListType || 'inspection');
                }
            } else {
                console.error('切换工序失败:', response.msg);
                Toast.fail(response.msg || '切换工序失败');
            }
        } catch (error) {
            console.error('切换工序失败:', error);
            Toast.fail('切换工序失败，请重试');
        }
    };

    const handleReportWork = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        const workQty = parseInt(workQuantity) || 0;
        const fatalQty = parseInt(fatalQuantity) || 0;

        if (workQty === 0 && fatalQty === 0) {
            Toast.fail('请输入报工数量或报废数量');
            return;
        }

        try {
            const response = await pushWorkApi({
                work_quantity: workQty,
                fatal_quantity: fatalQty,
                task_id: taskDetailData.task.id,
            });

            if (response.code === 200) {
                Toast.success(response.msg || '报工成功');
                // 重新获取任务详情
                await fetchTaskDetail(taskDetailData.task.batch_order_num);
                setWorkQuantity('0');
                setFatalQuantity('0');
            } else {
                Toast.fail(response.msg || '报工失败');
            }
        } catch (error) {
            console.error('报工失败:', error);
            Toast.fail('报工失败，请重试');
        }
    };

    const handleInStation = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            let response;
            if (taskDetailData.task.station_state === false) {
                // 未进站状态 - 调用进站接口
                console.log('调用进站接口');
                response = await inStationApi(taskDetailData.task.id);
            } else {
                // 已进站状态 - 调用出站接口
                console.log('调用出站接口');
                response = await outStationApi(taskDetailData.task.id);
            }

            if (response.code === 200) {
                const actionText = taskDetailData.task.station_state ? '出站' : '进站';
                Toast.success(response.msg || `${actionText}成功`);
                // 重新获取任务详情
                await fetchTaskDetail(taskDetailData.task.batch_order_num);
            } else {
                Toast.fail(response.msg || '操作失败');
            }
        } catch (error) {
            console.error('进站/出站失败:', error);
            Toast.fail('操作失败，请重试');
        }
    };

    const handleBackPress = () => {
        console.log('返回按钮被点击');
        if (onBackPress) {
            onBackPress();
        }
    };

    const handleGetWorkList = async (type: 'inspection' | 'records' = 'inspection') => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        // 获取当前工序的mbom_id
        const currentBom = taskDetailData.bom_list?.[currentProcessIndex];
        if (!currentBom) {
            Toast.fail('当前工序信息不存在');
            return;
        }

        // 先隐藏交接班列表，确保显示报检列表
        setShowHandoverList(false);
        setHandoverListData([]);

        // 设置加载状态和列表类型，这样会显示加载中的状态而不是首页
        setIsLoadingWorkList(true);
        setWorkListType(type);
        setShowWorkList(true); // 立即显示列表区域，但显示加载状态

        try {
            const response = await getWorkListApi({
                batch_order_id: taskDetailData.task.batch_order_id,
                mbom_id: currentBom.id
            });

            if (response.code === 200) {
                console.log('获取报工列表成功');
                setWorkListData(response.data || []);
            } else {
                console.error('获取报工列表失败:', response.msg);
                Toast.fail(response.msg || '获取报工列表失败');
                // 如果失败，隐藏列表区域
                setShowWorkList(false);
            }
        } catch (error) {
            console.error('获取报工列表失败:', error);
            Toast.fail('获取报工列表失败，请重试');
            // 如果失败，隐藏列表区域
            setShowWorkList(false);
        } finally {
            setIsLoadingWorkList(false);
        }
    };

    const handleBackToWork = () => {
        setShowWorkList(false);
        setWorkListData([]);
        setWorkListType(null);
        setShowHandoverList(false);
        setHandoverListData([]);
    };

    const handleTableInspect = async (workId: string) => {
        try {
            console.log('表格报检按钮被点击，工作ID:', workId);
            const response = await pushIPQCApi(workId);

            if (response.code === 200) {
                Toast.success(response.msg || '报检成功');
                // 重新获取报工列表以更新状态
                await handleGetWorkList();
            } else {
                Toast.fail(response.msg || '报检失败');
            }
        } catch (error) {
            console.error('报检失败:', error);
            Toast.fail('报检失败，请重试');
        }
    };

    const handleCallDevice = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('设备呼叫按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callDeviceApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '设备呼叫成功');
            } else {
                Toast.fail(response.msg || '设备呼叫失败');
            }
        } catch (error) {
            console.error('设备呼叫失败:', error);
            Toast.fail('设备呼叫失败，请重试');
        }
    };

    const handleCallLogistics = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('呼叫物流按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callLogisticsApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '呼叫物流成功');
            } else {
                Toast.fail(response.msg || '呼叫物流失败');
            }
        } catch (error) {
            console.error('呼叫物流失败:', error);
            Toast.fail('呼叫物流失败，请重试');
        }
    };

    const handleChangeTray = () => {
        setShowTrayModal(true);
    };

    const handleTrayModalCancel = () => {
        setShowTrayModal(false);
        setTrayNum('');
    };

    const handleTrayModalConfirm = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        if (!trayNum.trim()) {
            Toast.fail('请输入托盘号');
            return;
        }

        try {
            console.log('绑定托盘，批次订单号:', taskDetailData.task.batch_order_num, '托盘号:', trayNum);
            const response = await bindMesTrayApi({
                batch_order_num: taskDetailData.task.batch_order_num,
                tray_num: trayNum.trim()
            });

            if (response.code === 200) {
                Toast.success(response.msg || '托盘绑定成功');
                setShowTrayModal(false);
                setTrayNum('');
            } else {
                Toast.fail(response.msg || '托盘绑定失败');
            }
        } catch (error) {
            console.error('托盘绑定失败:', error);
            Toast.fail('托盘绑定失败，请重试');
        }
    };

    const handleCallAccident = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('意外呼叫按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callAccidentApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '意外呼叫成功');
            } else {
                Toast.fail(response.msg || '意外呼叫失败');
            }
        } catch (error) {
            console.error('意外呼叫失败:', error);
            Toast.fail('意外呼叫失败，请重试');
        }
    };

    const handleCallMaterialClaim = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('呼叫物料按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callMaterialClaimApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '呼叫物料成功');
            } else {
                Toast.fail(response.msg || '呼叫物料失败');
            }
        } catch (error) {
            console.error('呼叫物料失败:', error);
            Toast.fail('呼叫物料失败，请重试');
        }
    };

    const handleCallToolsClaim = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('呼叫工装按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callToolsClaimApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '呼叫工装成功');
            } else {
                Toast.fail(response.msg || '呼叫工装失败');
            }
        } catch (error) {
            console.error('呼叫工装失败:', error);
            Toast.fail('呼叫工装失败，请重试');
        }
    };

    const handleCallKnifeClaim = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('呼叫刀具按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callKnifeClaimApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '呼叫刀具成功');
            } else {
                Toast.fail(response.msg || '呼叫刀具失败');
            }
        } catch (error) {
            console.error('呼叫刀具失败:', error);
            Toast.fail('呼叫刀具失败，请重试');
        }
    };

    const handleCallMaterialRefund = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('归还物料按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callMaterialRefundApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '归还物料成功');
            } else {
                Toast.fail(response.msg || '归还物料失败');
            }
        } catch (error) {
            console.error('归还物料失败:', error);
            Toast.fail('归还物料失败，请重试');
        }
    };

    const handleCallToolsRefund = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('归还工装按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callToolsRefundApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '归还工装成功');
            } else {
                Toast.fail(response.msg || '归还工装失败');
            }
        } catch (error) {
            console.error('归还工装失败:', error);
            Toast.fail('归还工装失败，请重试');
        }
    };

    const handleCallKnifeRefund = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        try {
            console.log('归还刀具按钮被点击，任务ID:', taskDetailData.task.id);
            const response = await callKnifeRefundApi(taskDetailData.task.id);

            if (response.code === 200) {
                Toast.success(response.msg || '归还刀具成功');
            } else {
                Toast.fail(response.msg || '归还刀具失败');
            }
        } catch (error) {
            console.error('归还刀具失败:', error);
            Toast.fail('归还刀具失败，请重试');
        }
    };

    const handlePushFAI = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }
        try {
            const response = await pushFAIApi(taskDetailData.task.id);
            if (response.code === 200) {
                Toast.success(response.msg || '首检成功');
                await fetchTaskDetail(taskDetailData.task.batch_order_num);
            } else {
                Toast.fail(response.msg || '首检失败');
            }
        } catch (error) {
            console.error('首检失败:', error);
            Toast.fail('首检失败，请重试');
        }
    };

    const handleGetHandoverList = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        // 先隐藏报检列表，确保显示交接班列表
        setShowWorkList(false);
        setWorkListData([]);

        // 设置加载状态，这样会显示加载中的状态而不是首页
        setIsLoadingHandoverList(true);
        setShowHandoverList(true); // 立即显示列表区域，但显示加载状态

        try {
            const response = await getMesTaskHandoverListApi(taskDetailData.task.batch_order_id);

            if (response.code === 200) {
                console.log('获取交接班列表成功');
                setHandoverListData(response.data || []);
            } else {
                console.error('获取交接班列表失败:', response.msg);
                Toast.fail(response.msg || '获取交接班列表失败');
                // 如果失败，隐藏列表区域
                setShowHandoverList(false);
            }
        } catch (error) {
            console.error('获取交接班列表失败:', error);
            Toast.fail('获取交接班列表失败，请重试');
            // 如果失败，隐藏列表区域
            setShowHandoverList(false);
        } finally {
            setIsLoadingHandoverList(false);
        }
    };

    const handleBackToWorkFromHandover = () => {
        setShowHandoverList(false);
        setHandoverListData([]);
    };

    const handlePreviewImage = (imageUrl: string) => {
        setPreviewImageUrl(imageUrl);
        setShowImageModal(true);
    };

    const handleCloseImageModal = () => {
        setShowImageModal(false);
        setPreviewImageUrl('');
    };

    const handleShowHandoverModal = () => {
        setShowHandoverModal(true);
    };

    const handleCloseHandoverModal = () => {
        setShowHandoverModal(false);
        setHandoverRemark('');
        setHandoverImages([]);
    };

    const handleHandoverImageUpload = () => {
        if (handoverImages.length >= 3) {
            Toast.fail('最多只能上传3张图片');
            return;
        }

        const options = {
            mediaType: 'photo' as const,
            includeBase64: false,
            maxHeight: 2000,
            maxWidth: 2000,
        };

        Alert.alert(
            '选择图片来源',
            '请选择图片来源',
            [
                { text: '取消', style: 'cancel' },
                { text: '拍照', onPress: () => launchCamera(options, handleHandoverImageResponse) },
                { text: '从相册选择', onPress: () => launchImageLibrary(options, handleHandoverImageResponse) },
            ]
        );
    };

    const handleHandoverImageResponse = (response: ImagePickerResponse) => {
        if (response.didCancel) {
            return;
        } else if (response.errorCode) {
            Toast.fail('选择图片失败');
            return;
        } else if (response.assets && response.assets[0]) {
            const imageUri = response.assets[0].uri;
            if (imageUri) {
                setHandoverImages(prev => [...prev, imageUri]);
            }
        }
    };

    const handleHandoverConfirm = async () => {
        if (!taskDetailData || !taskDetailData.task) {
            Toast.fail('任务数据不存在');
            return;
        }

        if (!handoverRemark.trim()) {
            Toast.fail('请输入交接内容');
            return;
        }

        try {
            const params = {
                task_id: taskDetailData.task.id,
                remark: handoverRemark.trim(),
                link_list: handoverImages.map(imageUri => ({ link: imageUri }))
            };

            const response = await saveOrUpdateMesTaskHandoverApi(params);

            if (response.code === 200) {
                Toast.success(response.msg || '交接成功');
                handleCloseHandoverModal();
                // 重新获取交接班列表
                await handleGetHandoverList();
            } else {
                Toast.fail(response.msg || '交接失败');
            }
        } catch (error) {
            console.error('交接失败:', error);
            Toast.fail('交接失败，请重试');
        }
    };

    const renderProcessFlow = () => {
        if (!taskDetailData || !taskDetailData.bom_list) return null;

        return (
            <View style={styles.processFlow}>
                <ScrollView
                    horizontal
                    showsHorizontalScrollIndicator={false}
                    contentContainerStyle={styles.processScrollView}
                >
                    <View style={styles.processRow}>
                        {taskDetailData.bom_list.map((bom: any, index: number) => (
                            <React.Fragment key={bom.id}>
                                <TouchableOpacity onPress={() => handleProcessPress(index, bom)}>
                                    <View style={styles.processItem}>
                                        <Image
                                            source={{ uri: bom.process_icon }}
                                            style={styles.processIcon}
                                            resizeMode="cover"
                                        />
                                        <Text style={styles.processName}>{bom.process_name}</Text>
                                        {index === currentProcessIndex && (
                                            <View style={styles.currentProcessIndicator} />
                                        )}
                                    </View>
                                </TouchableOpacity>
                                {index < taskDetailData.bom_list.length - 1 && (
                                    <Text style={styles.processArrow}>→</Text>
                                )}
                            </React.Fragment>
                        ))}
                    </View>
                </ScrollView>
            </View>
        );
    };

    const renderTaskCard = () => {
        if (!taskDetailData || !taskDetailData.task) return null;

        const task = taskDetailData.task;

        return (
            <View style={styles.taskCard}>
                <View style={styles.taskHeader}>
                    <Text style={styles.taskHeaderText}>任务编号: {task.batch_order_num}</Text>
                    <Text style={styles.taskHeaderText}>产品编号: {task.product_name}</Text>
                </View>

                <View style={styles.kpiRow}>
                    <View style={styles.kpiItem}>
                        <Text style={styles.kpiValue}>{task.work_quantity}</Text>
                        <Text style={styles.kpiLabel}>已报工</Text>
                    </View>
                    <View style={styles.kpiItem}>
                        <Text style={styles.kpiValue}>{task.rework_quantity}</Text>
                        <Text style={styles.kpiLabel}>已返工</Text>
                    </View>
                    <View style={styles.kpiItem}>
                        <Text style={styles.kpiValue}>{task.accept_quantity}</Text>
                        <Text style={styles.kpiLabel}>让步接收</Text>
                    </View>
                    <View style={styles.kpiItem}>
                        <Text style={styles.kpiValue}>{task.fatal_quantity}</Text>
                        <Text style={styles.kpiLabel}>已报废</Text>
                    </View>
                    <View style={styles.kpiItem}>
                        <Text style={styles.kpiValue}>{task.quantity}</Text>
                        <Text style={styles.kpiLabel}>计划量</Text>
                    </View>
                </View>

                <View style={styles.inputRow}>
                    <Text style={styles.inputLabel}>报工数量</Text>
                    <TextInput
                        style={styles.inputField}
                        value={workQuantity}
                        onChangeText={setWorkQuantity}
                        placeholder="请输入报工数量"
                        keyboardType="numeric"
                    />
                </View>

                <View style={styles.inputRow}>
                    <Text style={styles.inputLabel}>报废数量</Text>
                    <TextInput
                        style={styles.inputField}
                        value={fatalQuantity}
                        onChangeText={setFatalQuantity}
                        placeholder="请输入报废数量"
                        keyboardType="numeric"
                    />
                </View>

                <TouchableOpacity style={styles.reportButton} onPress={handleReportWork}>
                    <Text style={styles.reportButtonText}>报工</Text>
                </TouchableOpacity>
            </View>
        );
    };

    const renderWorkListTable = () => {
        if (!showWorkList || workListType !== 'inspection' || workListData.length === 0) return null;

        return (
            <View style={styles.tableContainer}>
                <View style={styles.tableHeader}>
                    <Text style={styles.tableHeaderCell}>用户名</Text>
                    <Text style={styles.tableHeaderCell}>报工数量</Text>
                    <Text style={styles.tableHeaderCell}>让步数量</Text>
                    <Text style={styles.tableHeaderCell}>返工数量</Text>
                    <Text style={styles.tableHeaderCell}>报废数量</Text>
                    <Text style={styles.tableHeaderCell}>生产开始时间</Text>
                    <Text style={styles.tableHeaderCell}>生产结束时间</Text>
                    <Text style={styles.tableHeaderCell}>状态</Text>
                    <Text style={[styles.tableHeaderCell, { borderRightWidth: 0 }]}>操作</Text>
                </View>
                <ScrollView style={styles.tableBody}>
                    {workListData.map((item, index) => (
                        <View key={item.id || index} style={styles.tableRow}>
                            <Text style={styles.tableCell}>{item.user_name || '-'}</Text>
                            <Text style={styles.tableCell}>{item.work_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.self_accept_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.self_rework_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.self_fatal_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.produce_start || '-'}</Text>
                            <Text style={styles.tableCell}>{item.produce_end || '-'}</Text>
                            <Text style={styles.tableCell}>
                                {item.inspect_state ? '已检验' : '待检验'}
                            </Text>
                            <View style={[styles.tableCell, { borderRightWidth: 0 }]}>
                                <TouchableOpacity
                                    style={styles.inspectButton}
                                    onPress={() => handleTableInspect(item.id)}
                                >
                                    <Text style={styles.inspectButtonText}>报检</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    ))}
                </ScrollView>
            </View>
        );
    };

    const renderWorkRecordsTable = () => {
        if (!showWorkList || workListType !== 'records' || workListData.length === 0) return null;
        return (
            <View style={styles.tableContainer}>
                <View style={styles.tableHeader}>
                    <Text style={styles.tableHeaderCell}>用户名</Text>
                    <Text style={styles.tableHeaderCell}>报工数量</Text>
                    <Text style={styles.tableHeaderCell}>让步数量</Text>
                    <Text style={styles.tableHeaderCell}>返工数量</Text>
                    <Text style={[styles.tableHeaderCell]}>报废数量</Text>
                    <Text style={styles.tableHeaderCell}>生产开始时间</Text>
                    <Text style={[styles.tableHeaderCell, { borderRightWidth: 0 }]}>生产结束时间</Text>
                </View>
                <ScrollView style={styles.tableBody}>
                    {workListData.map((item, index) => (
                        <View key={item.id || index} style={styles.tableRow}>
                            <Text style={styles.tableCell}>{item.user_name || '-'}</Text>
                            <Text style={styles.tableCell}>{item.work_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.self_accept_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.self_rework_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.self_fatal_quantity || 0}</Text>
                            <Text style={styles.tableCell}>{item.produce_start || '-'}</Text>
                            <Text style={[styles.tableCell, { borderRightWidth: 0 }]}>{item.produce_end || '-'}</Text>
                        </View>
                    ))}
                </ScrollView>
            </View>
        );
    };

    const renderHandoverTable = () => {
        if (!showHandoverList) return null;

        return (
            <View>
                {/* 交接按钮 - 始终显示 */}
                <TouchableOpacity
                    style={styles.handoverButton}
                    onPress={handleShowHandoverModal}
                >
                    <Text style={styles.handoverButtonText}>交接</Text>
                </TouchableOpacity>

                {/* 交接班表格 - 只在有数据时显示 */}
                {handoverListData.length > 0 ? (
                    <View style={styles.tableContainer}>
                        <View style={styles.tableHeader}>
                            <Text style={styles.tableHeaderCell}>交接人</Text>
                            <Text style={styles.tableHeaderCell}>交接内容</Text>
                            <Text style={styles.tableHeaderCell}>交接时间</Text>
                            <Text style={styles.tableHeaderCell}>交接图片1</Text>
                            <Text style={styles.tableHeaderCell}>交接图片2</Text>
                            <Text style={[styles.tableHeaderCell, { borderRightWidth: 0 }]}>交接图片3</Text>
                        </View>
                        <ScrollView style={styles.tableBody}>
                            {handoverListData.map((item, index) => (
                                <View key={item.id || index} style={styles.tableRow}>
                                    <Text style={styles.tableCell}>{item.create_user_name || '-'}</Text>
                                    <Text style={styles.tableCell}>{item.remark || '-'}</Text>
                                    <Text style={styles.tableCell}>{item.create_time || '-'}</Text>
                                    <Text style={styles.tableCell}>
                                        {item.link_list && item.link_list[0] ? (
                                            <TouchableOpacity onPress={() => handlePreviewImage(item.link_list[0].link)}>
                                                <Text style={styles.viewImageText}>查看图片</Text>
                                            </TouchableOpacity>
                                        ) : '-'}
                                    </Text>
                                    <Text style={styles.tableCell}>
                                        {item.link_list && item.link_list[1] ? (
                                            <TouchableOpacity onPress={() => handlePreviewImage(item.link_list[1].link)}>
                                                <Text style={styles.viewImageText}>查看图片</Text>
                                            </TouchableOpacity>
                                        ) : '-'}
                                    </Text>
                                    <Text style={[styles.tableCell, { borderRightWidth: 0 }]}>
                                        {item.link_list && item.link_list[2] ? (
                                            <TouchableOpacity onPress={() => handlePreviewImage(item.link_list[2].link)}>
                                                <Text style={styles.viewImageText}>查看图片</Text>
                                            </TouchableOpacity>
                                        ) : '-'}
                                    </Text>
                                </View>
                            ))}
                        </ScrollView>
                    </View>
                ) : (
                    <View style={styles.loadingText}>
                        <Text style={styles.dataText}>暂无交接数据</Text>
                    </View>
                )}
            </View>
        );
    };

    const renderTrayModal = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={showTrayModal}
                onRequestClose={handleTrayModalCancel}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContainer}>
                        <Text style={styles.modalTitle}>设置托盘号</Text>

                        <View style={styles.modalInputContainer}>
                            <TextInput
                                style={styles.modalInput}
                                value={trayNum}
                                onChangeText={setTrayNum}
                                placeholder="请输入托盘号"
                                autoFocus={true}
                            />
                        </View>

                        <View style={styles.modalButtonContainer}>
                            <TouchableOpacity
                                style={[styles.modalButton, styles.modalCancelButton]}
                                onPress={handleTrayModalCancel}
                            >
                                <Text style={styles.modalCancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.modalButton, styles.modalConfirmButton]}
                                onPress={handleTrayModalConfirm}
                            >
                                <Text style={styles.modalConfirmButtonText}>确定</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        );
    };

    const renderImageModal = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={showImageModal}
                onRequestClose={handleCloseImageModal}
            >
                <View style={styles.imageModalOverlay}>
                    <TouchableOpacity
                        style={styles.imageModalContainer}
                        onPress={handleCloseImageModal}
                        activeOpacity={1}
                    >
                        <Image
                            source={{ uri: previewImageUrl }}
                            style={styles.previewImage}
                            resizeMode="contain"
                        />
                        <TouchableOpacity
                            style={styles.closeImageButton}
                            onPress={handleCloseImageModal}
                        >
                            <Text style={styles.closeImageButtonText}>×</Text>
                        </TouchableOpacity>
                    </TouchableOpacity>
                </View>
            </Modal>
        );
    };

    const renderHandoverModal = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={showHandoverModal}
                onRequestClose={handleCloseHandoverModal}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContainer}>
                        <Text style={styles.modalTitle}>交接</Text>

                        {/* 交接内容输入框 */}
                        <View style={styles.modalInputContainer}>
                            <TextInput
                                style={styles.modalInput}
                                value={handoverRemark}
                                onChangeText={setHandoverRemark}
                                placeholder="请输入交接内容"
                                multiline={true}
                                numberOfLines={3}
                            />
                        </View>

                        {/* 交接图片上传区域 */}
                        <View style={styles.handoverImageContainer}>
                            <Text style={styles.handoverImageTitle}>交接图片</Text>
                            <View style={styles.handoverImagesRow}>
                                {/* 显示已上传的图片 */}
                                {handoverImages.map((imageUri, index) => (
                                    <View key={index} style={styles.handoverImageItem}>
                                        <TouchableOpacity
                                            onPress={() => {
                                                setPreviewImageUrl(imageUri);
                                                setShowImageModal(true);
                                            }}
                                        >
                                            <Image source={{ uri: imageUri }} style={styles.handoverUploadedImage} />
                                        </TouchableOpacity>
                                        <TouchableOpacity
                                            style={styles.handoverRemoveImageButton}
                                            onPress={() => {
                                                setHandoverImages(prev => prev.filter((_, i) => i !== index));
                                            }}
                                        >
                                            <Text style={styles.handoverRemoveImageText}>×</Text>
                                        </TouchableOpacity>
                                    </View>
                                ))}
                                {/* 上传按钮 */}
                                {handoverImages.length < 3 && (
                                    <TouchableOpacity
                                        style={styles.handoverUploadArea}
                                        onPress={handleHandoverImageUpload}
                                    >
                                        <Text style={styles.handoverUploadText}>+</Text>
                                        <Text style={styles.handoverUploadSubText}>上传图片</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                        </View>

                        {/* 操作按钮 */}
                        <View style={styles.modalButtonContainer}>
                            <TouchableOpacity
                                style={[styles.modalButton, styles.modalCancelButton]}
                                onPress={handleCloseHandoverModal}
                            >
                                <Text style={styles.modalCancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.modalButton, styles.modalConfirmButton]}
                                onPress={handleHandoverConfirm}
                            >
                                <Text style={styles.modalConfirmButtonText}>确认</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        );
    };

    const renderBottomButtons = () => {
        const buttons = [
            ['首页', '进站', '图纸', '首检', '报检', '交接班', '更换托盘', '设备呼叫', '呼叫物流'],
            ['意外呼叫', '呼叫物料', '呼叫工装', '呼叫刀具', '归还物料', '归还工装', '归还刀具', '下载程序', '报工记录']
        ];

        return (
            <View style={styles.bottomButtons}>
                {buttons.map((row, rowIndex) => (
                    <View key={rowIndex} style={styles.buttonRow}>
                        {row.map((buttonText, index) => {
                            let buttonStyle: any = styles.actionButton;
                            let onPress = () => { };
                            let displayText = buttonText;

                            if (buttonText === '进站') {
                                // 根据station_state字段决定按钮样式和文字
                                if (taskDetailData?.task?.station_state === false) {
                                    // 未进站状态 - 绿色进站按钮
                                    buttonStyle = [styles.actionButton, styles.actionButtonGreen];
                                    displayText = '进站';
                                } else {
                                    // 已进站状态 - 红色出站按钮
                                    buttonStyle = [styles.actionButton, styles.actionButtonRed];
                                    displayText = '出站';
                                }
                                onPress = handleInStation;
                            } else if (buttonText === '首检') {
                                // 根据fai_state字段决定首检按钮是否可用
                                if (taskDetailData?.task?.fai_state === 1) {
                                    // fai_state为1时可用 - 蓝色按钮
                                    buttonStyle = styles.actionButton;
                                    onPress = handlePushFAI;
                                } else {
                                    // fai_state不为1时禁用 - 灰色按钮
                                    buttonStyle = [styles.actionButton, styles.actionButtonGray];
                                }
                            } else if (buttonText === '报检') {
                                onPress = () => handleGetWorkList('inspection');
                            } else if (buttonText === '交接班') {
                                onPress = handleGetHandoverList;
                            } else if (buttonText === '首页') {
                                onPress = handleBackToWork;
                            } else if (buttonText === '设备呼叫') {
                                onPress = handleCallDevice;
                            } else if (buttonText === '呼叫物流') {
                                onPress = handleCallLogistics;
                            } else if (buttonText === '更换托盘') {
                                onPress = handleChangeTray;
                            } else if (buttonText === '意外呼叫') {
                                onPress = handleCallAccident;
                            } else if (buttonText === '呼叫物料') {
                                onPress = handleCallMaterialClaim;
                            } else if (buttonText === '呼叫工装') {
                                onPress = handleCallToolsClaim;
                            } else if (buttonText === '呼叫刀具') {
                                onPress = handleCallKnifeClaim;
                            } else if (buttonText === '归还物料') {
                                onPress = handleCallMaterialRefund;
                            } else if (buttonText === '归还工装') {
                                onPress = handleCallToolsRefund;
                            } else if (buttonText === '归还刀具') {
                                onPress = handleCallKnifeRefund;
                            } else if (buttonText === '报工记录') {
                                onPress = () => handleGetWorkList('records');
                            }

                            return (
                                <TouchableOpacity
                                    key={index}
                                    style={buttonStyle}
                                    onPress={onPress}
                                >
                                    <Text style={styles.actionButtonText}>{displayText}</Text>
                                </TouchableOpacity>
                            );
                        })}
                    </View>
                ))}
            </View>
        );
    };

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.header}>
                <Image
                    source={require('../../../../assets/terminal/home-header.png')}
                    style={styles.headerBackground}
                    resizeMode="cover"
                />
                <View style={styles.headerContent}>
                    {/* <Image
                        source={require('../../../../assets/terminal/home-logo.png')}
                        style={styles.logo}
                        resizeMode="contain"
                    /> */}
                    <Text style={styles.headerText}>MES终端服务系统</Text>
                </View>
                <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
                    <Image source={require('../../../../assets/fanhui.png')} style={styles.backIcon} />
                </TouchableOpacity>
            </View>

            {/* 固定的工序流程区域 */}
            {taskDetailData && renderProcessFlow()}

            {/* 可滚动的内容区域 */}
            <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
                <View style={styles.contentArea}>
                    {isLoading && (
                        <Text style={styles.loadingText}>正在获取任务详情...</Text>
                    )}

                    {taskDetailData && (
                        <>
                            {showWorkList ? (
                                <>
                                    {isLoadingWorkList && (
                                        <Text style={styles.loadingText}>正在获取报工列表...</Text>
                                    )}
                                    {renderWorkListTable()}
                                    {renderWorkRecordsTable()}
                                </>
                            ) : showHandoverList ? (
                                <>
                                    {isLoadingHandoverList && (
                                        <Text style={styles.loadingText}>正在获取交接班列表...</Text>
                                    )}
                                    {renderHandoverTable()}
                                </>
                            ) : (
                                renderTaskCard()
                            )}
                        </>
                    )}
                </View>
            </ScrollView>

            {/* 固定的底部按钮区域 */}
            {taskDetailData && renderBottomButtons()}
            {renderTrayModal()}
            {renderImageModal()}
            {renderHandoverModal()}
        </SafeAreaView>
    );
};

export default ProductionReport;